import {
  settestOAuthUser,
  SettlementByType,
  TaskType,
  findUserByParam,
  TaskSpecial,
  singleSave
} from "@/api/sendsingle"
import { randomStr } from "@/utils"

import selectPopup from "../components/selectPopup"

import saveJson from "../template/save"

export default {
  components: {
    selectPopup
  },
  data() {
    return {
      // 单元格绑定值
      cellData: {
        taskName: "",
        deliverable: "",
        describe: ""
      },

      // 弹窗加载状态
      loadStatus: {
        loading: false,
        finished: true
      },

      // 是否展示弹窗
      showpopup: false,
      // 是否展示日历
      calendarShow: false,

      plandate: "请选择起止时间",

      // 弹窗数据集
      popupObj: {},
      // 接口数据集
      DataObj: {},

      // 当前页码
      changePage: 1,

      // 保存参数
      saveObj: {},
      // 主键id
      saveId: randomStr(),

      specialObj: {
        show: false,
        label: "",
        isReport: false,
        value: ""
      }
    }
  },

  watch: {
    showpopup(n) {
      if (!n) {
        this.popupObj = Object.assign(this.popupObj, {})
      }
    }
  },

  created() {
    this.saveObj = JSON.parse(JSON.stringify(saveJson))
    this.init()
  },

  methods: {
    async init() {
      // 设置用户
      this.setLoading()

      let status = process.env.NODE_ENV
      if (status === "development_pd") await settestOAuthUser("201205")
      else localStorage.setItem("token", this.$route.query.token)

      // 获取人员列表
      this.getPerson()

      // 任务类型
      TaskType().then((res) => {
        this.setData(res, "task")
      })
      // 结算类型
      SettlementByType().then((res) => {
        this.setData(res, "settlement_1")
      })
      // 结算分级
      SettlementByType(3).then((res) => {
        this.setData(res, "settlement_2")
      })
      // 结算标签
      SettlementByType(2).then((res) => {
        this.setData(res, "settlement_3")
        this.clearLoading()
      })
    },

    isOtherSystem() {
      if (Object.keys(this.$route.query).length > 3) {
        let query = this.$route.query
        this.cellData.taskName = query.name
        this.cellData.check = query.assignerName
        this.saveObj.assignerName = query.assignerName
        this.saveObj.assigner = query.assigner
        this.DataObj["person"].forEach((item) => {
          if (item.value === query.assigner) this.saveObj.assignerNameArr[0] = { ...item }
        })
        this.saveObj.settletypecode = query.settletypecode
        this.DataObj["person"].forEach((item) => {
          if (item.settletypecode == query.settletypecode)
            this.cellData["settlementType"] = item.label
        })
        this.cellData.describe = query.description
      }
    },

    // DataObj添加数据
    setData(res, name) {
      if (res.code === 0) {
        this.DataObj[name] = res.data
      }
    },

    /**
     *
     * 获取人员列表
     * @param {String} param 搜索条件
     * @param {Number} page 页码
     */
    getPerson(param = "", page = 1) {
      // 当有搜索条件的时候，不使用分页
      if (page === 1 && param === "") {
        findUserByParam(param, page).then((res) => {
          if (res.code === 0) {
            this.DataObj["person"] = []
            this.DataObj["person"] = res.data.rows
            this.isOtherSystem()
          }
        })
      } else if (page > 1 && param === "") {
        findUserByParam(param, page).then((res) => {
          if (res.code === 0 && res.data.rows.length > 0) {
            this.popupObj["showlist"].push(...res.data.rows)
            this.loadStatus.finished = false
          } else this.loadStatus.finished = true

          this.loadStatus.loading = false
        })
      } else if (param !== "") {
        this.setLoading()
        findUserByParam(param, page).then((res) => {
          this.popupObj = Object.assign({}, this.popupObj, {
            showlist: res.data.rows
          })
          this.clearLoading()
        })
      }

      this.loadStatus.loading = false
    },

    // 设置Loading
    setLoading() {
      return this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0
      })
    },

    // 关闭Loading
    clearLoading() {
      this.$toast.clear()
      this.$toast.success("加载完成")
    },

    // 展示popup
    show(type) {
      this.popupObj["type"] = type
      switch (type) {
        case 1:
          this.popupObj["title"] = "执行人"
          this.popupObj["needSearch"] = true
          this.popupObj["showlist"] = this.DataObj.person || []
          this.popupObj["showkey"] = "label"
          this.popupObj["needLabel"] = true
          this.popupObj["labelkey"] = "subLabel"
          this.loadStatus.finished = false
          break
        case 2:
          this.popupObj["title"] = "验收人"
          this.popupObj["needSearch"] = true
          this.popupObj["showlist"] = this.DataObj.person || []
          this.popupObj["showkey"] = "label"
          this.popupObj["needLabel"] = true
          this.popupObj["labelkey"] = "subLabel"
          this.loadStatus.finished = false
          break
        case 3:
          this.popupObj["title"] = "任务类型"
          this.popupObj["needSearch"] = false
          this.popupObj["showlist"] = this.DataObj.task || []
          this.popupObj["showkey"] = "name"
          this.loadStatus.finished = true
          break
        case 4:
          this.popupObj["title"] = "结算类型"
          this.popupObj["needSearch"] = false
          this.popupObj["showlist"] = this.DataObj.settlement_1 || []
          this.popupObj["showkey"] = "label"
          this.loadStatus.finished = true
          break
        case 5:
          this.popupObj["title"] = "结算标签"
          this.popupObj["needSearch"] = false
          this.popupObj["showlist"] = this.DataObj.settlement_2 || []
          this.popupObj["showkey"] = "label"
          this.loadStatus.finished = true
          break
        case 6:
          this.popupObj["title"] = "结算分级"
          this.popupObj["needSearch"] = false
          this.popupObj["showlist"] = this.DataObj.settlement_3 || []
          this.popupObj["showkey"] = "label"
          this.loadStatus.finished = true
          break
      }

      this.showpopup = true
    },

    /**
     * 确认选择
     * @param {Object} item 搜索条件
     * @param {String} type 传入的popup类型
     */
    handlePopupCallback(item, type) {
      switch (type) {
        case 1:
          this.cellData["implement"] = item.label
          this.saveObj.principalName = item.label
          this.saveObj.principal = item.value
          this.saveObj.principalNameArr[0] = { ...item }
          break
        case 2:
          this.cellData["check"] = item.label
          this.saveObj.assignerName = item.label
          this.saveObj.assigner = item.value
          this.saveObj.assignerNameArr[0] = { ...item }
          break
        case 3:
          this.cellData["taskType"] = item.name
          this.saveObj.task2taskTyp[0] = {
            task: this.saveId,
            typ: item.id
          }

          // 查询是否有特殊属性
          TaskSpecial(item.id).then((res) => {
            // 如果存在特殊属性，则有data字段，反正，没有data字段
            if (res.data) {
              let obj = res.data[0]

              this.saveObj.taskTypSpecAttriVals[0] = {
                id: this.saveId,
                task: item.id,
                attrbuteId: obj.attrName,
                attributeName: obj.attrType,
                attributeValue: this.specialObj.value
              }

              this.specialObj.show = true
              this.specialObj.label = obj.attrName
              this.specialObj.isReport = obj.isReport === "Y" ? true : false
            } else {
              this.saveObj.taskTypSpecAttriVals = []

              this.specialObj = {
                show: false,
                label: "",
                isReport: false,
                value: ""
              }
            }
          })
          break
        case 4:
          this.cellData["settlementType"] = item.label
          this.saveObj.settletypecode = item.value
          break
        case 5:
          this.cellData["settlementTip"] = item.label
          this.saveObj.shixiangbiaoqian = item.value
          break
        case 6:
          this.cellData["settlementLevel"] = item.label
          this.saveObj.settleLevel = item.label
          break
      }

      this.showpopup = false
    },

    // 时间格式
    formatDate(date) {
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    },

    // 确认结算时间
    onConfirm(date) {
      const [start, end] = date
      this.calendarShow = false
      this.plandate = ` ${this.formatDate(start)}  ---  ${this.formatDate(end)}`

      let outputDate = (item) => {
        return item.trim().replace(/\//g, "-") + " 00:00:00"
      }

      let sTime = outputDate(this.plandate.split("---")[0])

      let eTime = outputDate(this.plandate.split("---")[1])

      this.saveObj.begin = sTime
      this.saveObj.end = eTime
    },

    load(type) {
      if (type === 1 || type === 2) {
        this.loadStatus.finished = false
        this.changePage++
        this.getPerson("", this.changePage)
      }
    },

    handleSave() {
      this.saveObj.id = this.saveId
      this.saveObj.description = this.cellData.describe
      this.saveObj.name = this.cellData.taskName
      this.saveObj.submit = this.cellData.deliverable
      this.saveObj.taskTypSpecAttriVals.length > 0
        ? (this.saveObj.taskTypSpecAttriVals[0].attributeValue = this.specialObj.value)
        : ""

      singleSave(this.saveObj).then((res) => {
        if (res.code === 0) {
          this.$toast.success(res.msg)
          setTimeout(() => {
            window.location.reload()
          }, 2000)
        } else this.$toast.fail(res.msg)
      })
    }
  }
}
